//
//  UIEngine.m
//  
//
//  Created by xuyue on 12-8-16.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "HPUIEngine.h"
#import "DefineUtil.h"
#import "CategoryUtil.h"
#import "Utility.h"
#import "ZZTongUIEngine.h"
#import "ZZTongClientEngine.h"
#import <MapKit/MapKit.h>
#import "ZZTongDefine.h"
//#import "HPSwiperService.h" //mcm

@implementation HPUIEngine
@synthesize hpUIDelegate;
@synthesize scrWidth;
@synthesize scrHeight;
@synthesize mAlertView;
@synthesize mAlertData;
@synthesize keyBoardSize;
@synthesize hpUtilDelegate;
@synthesize mAlertController;
@synthesize waittingView;

#define ROOT_SCREEN     @"hp_root_screen"
#define ROOT_LOGIN      @"hp_root_login"
#define BOOL_YES        @"b_YES"
#define BOOL_NO         @"b_NO"

static HPUIEngine* instance = nil;

+ (HPUIEngine*)getInstance{
	if (!instance) {
		instance = [[HPUIEngine alloc] init];
        // 设置导航条
	}
	return instance;
}

+ (void)releaseInstance{
	if (instance) {
		[instance release];
		instance = nil;
	}
}

-(id)init{
    if ((self = [super init])) {
       
//        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
//            [NOTIFICATION addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardDidShowNotification object:nil];
//            [NOTIFICATION addObserver:self selector:@selector(keyBoardHide:) name:UIKeyboardDidHideNotification object:nil];
//        } else {
            [NOTIFICATION addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardWillShowNotification object:nil];
            [NOTIFICATION addObserver:self selector:@selector(keyBoardHide:) name:UIKeyboardWillHideNotification object:nil];
//        }
        
        [NOTIFICATION addObserver:self selector:@selector(textFieldBeginEditing:) name:UITextFieldTextDidBeginEditingNotification object:nil];
        [NOTIFICATION addObserver:self selector:@selector(textViewBeginEditing:) name:UITextViewTextDidBeginEditingNotification object:nil];
        
        scrWidth =  [UIScreen mainScreen].bounds.size.width;
        scrHeight = [UIScreen mainScreen].bounds.size.height;
    }
    return self;
}

- (void)dealloc{    
    //取消注册
//    [NOTIFICATION removeObserver:self name:UIKeyboardDidShowNotification object:nil];
//    [NOTIFICATION removeObserver:self name:UIKeyboardDidHideNotification object:nil];
//	
//    [NOTIFICATION removeObserver:self name:UITextFieldTextDidBeginEditingNotification object:nil];
//    [NOTIFICATION removeObserver:self name:UITextFieldTextDidEndEditingNotification object:nil];

    [NOTIFICATION removeObserver:self];
    [self removeAlert];
    self.mAlertView = nil;
    self.hpUIDelegate = nil;
    self.hpUtilDelegate = nil;
    self.mAlertController = nil;
    self.waittingView = nil;
    
	[super dealloc];
}

/**
 * 显示程序启动欢迎页面
 */
- (void)showWelcomeScreen{
    if (!self.hpUIDelegate){
        return;
    }
    
    [self.hpUIDelegate showWelcomeScreen];
}

- (void)doRemoveWelcomeScreen{
    [self.hpUIDelegate removeWelcomeScreen];
}

 -(void)removeWelcomeScreen{
    if (!self.hpUIDelegate) {
        return;
    }
     
    [self performSelectorOnMainThread:@selector(doRemoveWelcomeScreen) withObject:nil waitUntilDone:YES];
}

- (UIViewController*)createScreen:(NSString*)screenName params:(NSDictionary*)screenData{
    if (!self.hpUIDelegate) {
        return nil;
    }
    
    if (!screenName) {
        return nil;
    }
    
    if ([self.hpUIDelegate respondsToSelector:@selector(createScreen:withData:)]) {
        return [self.hpUIDelegate createScreen:screenName withData:screenData];
    }
    
    Class scrClass = NSClassFromString(screenName);
    if (!scrClass) {
        return nil;
    }
    
    Screen* scr = [[scrClass alloc] init];
    scr.screenData = screenData;
    scr.screenName = screenName;
    return [scr autorelease];
}


- (void)doShowScreen:(NSString*)screenName params:(NSDictionary*)screenData{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    
	Screen* scr = (Screen*)[self createScreen:screenName params:screenData];
	
    if (self.hpUIDelegate) {
        scr.screenName = screenName;
        [self.hpUIDelegate showScreen:scr];
    }
    
    if (self.waittingView) {
        [ZZT_UIENG getCurrentNavigation].tabBarController.view.userInteractionEnabled = NO;
        scr.view.userInteractionEnabled = NO;
    }
    [pool release];
}
/**
 * UI页面的初始化及显示
 * 参数screenData：需要传递的参数
 */
- (void)showScreen:(NSString*)screenName params:(NSDictionary*)screenData{
    if ([NSThread isMainThread]) {
        [self doShowScreen:screenName params:screenData];
    }else{
        [self performSelectorOnMainThread:@selector(doShowScreen:params:) withObject:screenName withObject:screenData waitUntilDone:YES];
    }
    
}

- (void)showScreen:(NSString*)screenName{
    [self showScreen:screenName params:nil];
}

- (void)showIndex:(NSInteger)index{
//    dispatch_async(dispatch_get_main_queue(), ^{
//         [self showIndex:[NSNumber numberWithUnsignedInteger:index] params:nil];
//    });
    if ([NSThread isMainThread]) {
        [self showIndex:[NSNumber numberWithUnsignedInteger:index] params:nil];
    }else{
        [self performSelectorOnMainThread:@selector(showIndex:params:) withObject:[NSNumber numberWithUnsignedInteger:index] withObject:nil waitUntilDone:YES];
    }
    
}

- (void)showIndex:(NSNumber*)number params:(NSDictionary*)params{
    if (number.intValue < 0) {
        return;
    }
    
    if (!self.hpUIDelegate) {
        return;
    }
    
    if ([self.hpUIDelegate respondsToSelector:@selector(showScreenByIndex:params:)]) {
        [self.hpUIDelegate showScreenByIndex:number.intValue params:params];
    }
}

- (Screen*)topScreen{
    if (!self.hpUIDelegate) {
        return nil;
    }
    
    return (Screen*)[self.hpUIDelegate topScreen];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (!self.mAlertData){
        return;
    }
    
    NSArray* commandArray = self.mAlertData.alertCommandArray;
    if (!commandArray || [commandArray count] == 0) {
        return;
    }
    
    if (!self.mAlertData.mTarget){
        return;
    }
    
    AlertCommandData* commandData = [commandArray objectAtIndex:buttonIndex];
    if ([self.mAlertData.mTarget respondsToSelector:commandData.func]) {
        [self.mAlertData.mTarget performSelector:commandData.func];
    }
    self.mAlertData = nil;
}

- (void)willPresentAlertView:(UIAlertView *)alertView{
    if (self.mAlertData.leftPadding > 0.0f){
        if (alertView.subviews.count < 3) {
            return;
        }
        UIView * view = [alertView.subviews objectAtIndex:2];
        if(view && [view isKindOfClass:[UILabel class]]){
            UILabel* label = (UILabel*) view;
            label.textAlignment = NSTextAlignmentLeft;
            CGRect labelFrame = label.frame;
            labelFrame.origin.x += self.mAlertData.leftPadding;
            label.frame = labelFrame;
        }
    }
}

- (void)doShowAlert:(AlertData*)alertData{
    [self removeAlert];
    [self removeWaiting];
    
    double version = [[UIDevice currentDevice]systemVersion].doubleValue;
    if (version >=8.0) {
        self.mAlertController = [UIAlertController alertControllerWithTitle:alertData.title message:alertData.message preferredStyle:UIAlertControllerStyleAlert];
        if (!alertData.alertCommandArray || [alertData.alertCommandArray count] == 0) {
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [self.mAlertController addAction:action];
        }else{
            for (AlertCommandData* command in alertData.alertCommandArray) {
                UIAlertAction *action = [UIAlertAction actionWithTitle:command.title style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    if ([self.mAlertData.mTarget respondsToSelector:command.func]) {
                        [self.mAlertData.mTarget performSelector:command.func];
                    }
                    self.mAlertData = nil;
                }];
                [self.mAlertController addAction:action];
            }
        }
        
        [[HPUIENG getCurrentScreen]presentViewController:self.mAlertController animated:YES completion:nil];
    }else{
        UIAlertView* alertView = [[UIAlertView alloc] init];
        alertView.title = alertData.title;
        alertView.message = alertData.message;
        if (!alertData.alertCommandArray || [alertData.alertCommandArray count] == 0) {
            [alertView addButtonWithTitle:@"确定"];
        }else{
            for (AlertCommandData* command in alertData.alertCommandArray) {
                [alertView addButtonWithTitle:command.title];
            }
        }
    
        alertView.delegate = self;
        self.mAlertView = alertView;
        [self.mAlertView show];
        [alertView release];
    }
}

- (void)showAlert:(NSString*)title msg:(NSString*)msg{
    if (self.mAlertData.isMustOperate) {
        return;
    }
    
    AlertData* alertData = [[AlertData alloc] initAlertData:title message:msg];
    [self showAlertWithData:alertData];
    [alertData release];
}

- (void)showAlertWithData:(AlertData*)alertData{
    if (self.mAlertData.isMustOperate) {
        return;
    }
    self.mAlertData = alertData;
    if ([[NSThread currentThread] isMainThread]) {
        [self doShowAlert:alertData];
    } else {
        [self performSelectorOnMainThread:@selector(doShowAlert:) withObject:alertData waitUntilDone:NO];
    }
    
}
- (void)showAlert:(NSString *)msg{
    [self showAlert:@"提示" msg:msg];
}
- (void)showTips:(NSString*)msg{
    
}

- (void)doShowWating:(NSString*)msg{
    [self removeWaiting];
    
    HPWaittingView * waitting = [[HPWaittingView alloc]initWithMsg:msg];
    self.waittingView = waitting;
    [self.waittingView showView];
    [waitting release];
    
//    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
//    
//    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
//    if (version < 7.0){
//        [alertView setMessage:@"\n\n"];
//        
//        UIActivityIndicatorView* indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
//        CGRect tempRect = indicatorView.frame;
//        tempRect.origin.x = (280 - tempRect.size.width) / 2;
//        tempRect.origin.y = 20;
//        indicatorView.frame = tempRect;
//        
//        [alertView addSubview:indicatorView];
//        
//        [indicatorView startAnimating];
//        [indicatorView release];
//        
//        UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0, 80, 280, 20)];
//        label.text = msg;
//        label.backgroundColor = [UIColor clearColor];
//        label.textColor = [UIColor whiteColor];
//        label.textAlignment = NSTextAlignmentCenter;
//        [alertView addSubview:label];
//        [label release];
//        
//    }
//    
//    self.mAlertView = alertView;
//    [alertView release];
//
//    [self.mAlertView show];
}

- (void)showWaiting:(NSString*)msg{
//    if (self.mAlertData.isMustOperate) {
//        return;
//    }
    if ([[NSThread currentThread] isMainThread]) {
        [self doShowWating:msg];
    } else {
        [self performSelectorOnMainThread:@selector(doShowWating:) withObject:msg waitUntilDone:YES];
    }
}

- (void)showProgress:(NSString*)msg steps:(NSUInteger)steps
{
    if (self.mAlertData.isMustOperate) {
        return;
    }
    if ([[NSThread currentThread] isMainThread]) {
        HPAlertProgressView *alertView = [[HPAlertProgressView alloc] initProgressViewWithTitle:msg steps:steps];
        self.progressView = alertView;
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            HPAlertProgressView *alertView = [[HPAlertProgressView alloc] initProgressViewWithTitle:msg steps:steps];
            self.progressView = alertView;
        });
    }
    
}

- (void)showToast:(NSString*)msg{
    if (self.mAlertData.isMustOperate) {
        return;
    }
    AlertData* alertData = [[AlertData alloc] initAlertData:nil message:msg];
    [self showAlertWithData:alertData];
    [alertData release];
}

- (void)doRemoveAlert{
    double version = [[UIDevice currentDevice]systemVersion].doubleValue;
    if (version >= 8.0) {
        if (self.mAlertController) {
            [self.mAlertController dismissViewControllerAnimated:YES completion:nil];
            self.mAlertController = nil;
        }
    }else{
        if (self.mAlertView) {
            [self.mAlertView dismissWithClickedButtonIndex:0 animated:NO];
            self.mAlertView = nil;
        }
    }
}

- (void)removeAlert{
    if (self.mAlertData.isMustOperate) {
        return;
    }
    
    if ([[NSThread currentThread] isMainThread]) {
        [self doRemoveAlert];
    } else{
        [self performSelectorOnMainThread:@selector(doRemoveAlert) withObject:nil waitUntilDone:YES];
    }
    if (self.progressView) {
        if ([[NSThread currentThread] isMainThread]) {
            [self.progressView removeFromSuperview];
            self.progressView = nil;
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.progressView removeFromSuperview];
                self.progressView = nil;
            });
        }
        
    }
}

- (void)removeTips{
    [self removeAlert];
}
- (void)doRemoveWaiting{
    if (self.waittingView) {
        UITabBarController* tabCon = [ZZT_UIENG getCurrentNavigation].tabBarController;
        if (tabCon && tabCon.view) {
            tabCon.view.userInteractionEnabled = YES;
        }
        [HPUIENG getCurrentScreen].view.userInteractionEnabled = YES;
        
        [self.waittingView removeView];
        self.waittingView = nil;
    }
    if (self.progressView) {
        if ([[NSThread currentThread] isMainThread]) {
            [self.progressView removeFromSuperview];
            self.progressView = nil;
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.progressView removeFromSuperview];
                self.progressView = nil;
            });
        }
        
    }
}
- (void)removeWaiting{
    
    if ([[NSThread currentThread] isMainThread]) {
        [self doRemoveWaiting];
    } else{
        [self performSelectorOnMainThread:@selector(doRemoveWaiting) withObject:nil waitUntilDone:YES];
    }
}

- (void)doPopScreen:(NSObject*)obj{
    if (!self.hpUIDelegate){
        return;
    }
    
    if (!obj) {
        [self.hpUIDelegate popScreen:1 animations:YES];
        return;
    }
    
    if ([obj isKindOfClass:[NSNumber class]]) {
        [self.hpUIDelegate popScreen:[(NSNumber*)obj intValue] animations:YES];
    }else if ([obj isKindOfClass:[UIViewController class]]){
        [self.hpUIDelegate popToScreen:(UIViewController*)obj animations:YES];
    }else if ([obj isKindOfClass:[NSString class]]){
        NSString* str = (NSString*)obj;
        if ([str isEqualToString:ROOT_SCREEN]) {
            [self.hpUIDelegate popToRootScreen:YES];
        } else if ([str isEqualToString:BOOL_YES]){
            [self.hpUIDelegate popScreen:1 animations:YES];
        } else if ([str isEqualToString:BOOL_NO]){
            [self.hpUIDelegate popScreen:1 animations:NO];
        }else if([str isEqualToString:ROOT_LOGIN]){
            [self.hpUIDelegate popToLoginScreen:YES];
        }
    }
}

/**
 * 返回到指定页面
 * 参数screenId：为数字时表示后退页面数，非数字时为跳回到制定id页面
 */
- (void)popScreen{
    [self performSelectorOnMainThread:@selector(doPopScreen:) withObject:nil waitUntilDone:YES];
}

- (void)popScreenWithAnimations:(BOOL)animations{
    [self performSelectorOnMainThread:@selector(doPopScreen:) withObject:BOOL_NO waitUntilDone:YES];
}

- (void)popScreenByNum:(int)num{
    [self performSelectorOnMainThread:@selector(doPopScreen:) withObject:[NSNumber numberWithInt:num] waitUntilDone:YES];
}

- (void)popScreenByViewController:(UIViewController*)viewController{
    [self performSelectorOnMainThread:@selector(doPopScreen:) withObject:viewController waitUntilDone:YES];
}

- (void)popToRootScreen{
    [self performSelectorOnMainThread:@selector(doPopScreen:) withObject:ROOT_SCREEN waitUntilDone:YES];
}
- (void)popToLoginScreen{
    [self performSelectorOnMainThread:@selector(doPopScreen:) withObject:ROOT_LOGIN waitUntilDone:YES];
}

- (Screen*)getCurrentScreen{
    if (!self.hpUIDelegate) {
        return nil;
    }
    
	Screen* scr = (Screen*)[self.hpUIDelegate topScreen];
	return scr;
}
/**
 * 显示发送短信页面
 * 参数msg：短信内容
 *    phone：联系人号码
 */
-(void)displaySMSComposerSheet:(NSString * ) msg  phoneNo:(NSString * ) phone
{
//    if (!self.hpUIDelegate) {
//        return;
//    }
//    
//	MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
//	picker.messageComposeDelegate = self;
//	picker.body = msg;
//    if (phone != NULL && [phone length] > 0) {
//        picker.recipients = [NSArray arrayWithObjects:phone, nil];
//    }
//    
//	Screen* scr = (Screen*)[self.hpUIDelegate topScreen];
////	[scr presentModalViewController:picker animated:YES];
//    [scr presentViewController:picker animated:YES completion:nil];
//	[picker release];
}

// 处理发送完的响应结果
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    if (!self.hpUIDelegate) {
        return;
    }
    
    Screen* scr = (Screen*)[self.hpUIDelegate topScreen];
    [scr dismissViewControllerAnimated:YES completion:nil];
    
    if (result == MessageComposeResultCancelled){
        LOG(@"Message cancelled");
    } else if (result == MessageComposeResultSent){
        LOG(@"Message sent");
    } else {
        LOG(@"Message failed");
    }
}


/**
 * 处理短信功能
 * 参数msg：短信内容
 *    phone：联系人号码
 */
-(void)showSMSPicker:(NSString * ) msg phoneNo:(NSString * ) phone{
    Class messageClass = (NSClassFromString(@"MFMessageComposeViewController"));
	UIAlertView * alert = nil;
	if (messageClass != nil) {
		// Check whether the current device is configured for sending SMS messages
		if ([messageClass canSendText]) {
            if ([phone isEqualToString:@"yys"]) {
                phone = [Utility getTelephonyPhone];
            }
			[self displaySMSComposerSheet:msg phoneNo:phone];
		}
		else {
			alert = [[UIAlertView alloc]initWithTitle:@"设备没有短信功能" message:nil delegate:self
									cancelButtonTitle:@"关闭" otherButtonTitles:nil];
		}
	}
	else {
		alert = [[UIAlertView alloc]initWithTitle:@"iOS版本过低,iOS4.0以上才支持程序内发送短信" message:nil delegate:self
								cancelButtonTitle:@"关闭" otherButtonTitles:nil];
	}
	if (alert != nil) {
		[alert show];
        [alert release];
	}
}



/**
 * 调用浏览器
 * 参数url：网页地址
 */
-(void)DoBrowsUI:(NSString * ) url{
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    
}


/**
 * 调用短信
 * 参数dict：短信相关数据
 */
-(void)DoSmsUI:(NSDictionary * )dict{
	NSString * msg = [dict objectForKey:@"msg"];
	NSString * phoneNumber = [dict objectForKey:@"phoneNumber"];
    [self showSMSPicker:msg phoneNo:phoneNumber];
    return;
}


/**
 * 调用电话
 * 参数call：电话号码
 */
-(void)DoCallUI:(NSString *) call{
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:call]];
}


/**
 * 退出程序
 */
-(void)DoExit{
    exit(0);
//    [[UIApplication sharedApplication] performSelector:@selector(terminateWithSuccess)];
}
- (void) textFieldBeginEditing:(NSNotification *)notification
{
    if (notification && notification.object && [notification.object isKindOfClass:[UITextField class]]) {
        Screen *scrn = (Screen*)[self.hpUIDelegate topScreen];
        [scrn textFieldBeginEditingForTextField:(UITextField *)notification.object];
    }
}

- (void) textViewBeginEditing:(NSNotification *)notification
{
    if (notification && notification.object && [notification.object isKindOfClass:[UITextView class]]) {
        Screen *scrn = (Screen*)[self.hpUIDelegate topScreen];
        [scrn textFieldBeginEditingForTextField:(UITextView *)notification.object];
    }
}

//-(void)textFieldEndEditing:(NSNotification*)anotification{
//    UITextField* tempTextField = anotification.object;
//    if (tempTextField) {
//        [tempTextField resignFirstResponder];
//    }
//}

//监听键盘显示事件，用于将页面向上弹起
-(void)keyBoardShow:(NSNotification *) anotification{
    if (!self.hpUIDelegate) {
        return;
    }
    
	NSDictionary * info=[anotification userInfo];
	NSValue * avalue=[info objectForKey:UIKeyboardFrameBeginUserInfoKey];
	//keyboared size
	CGSize keyboaredSize=[avalue CGRectValue].size;
    if (CGSizeEqualToSize(HPUIENG.keyBoardSize, CGSizeZero) ) {
        HPUIENG.keyBoardSize = keyboaredSize;
    }
    Screen * keyBordScreen = (Screen*)[self.hpUIDelegate topScreen];
	if (keyBordScreen!=nil) {
		[keyBordScreen popKeyBoardUI:keyboaredSize];
	}
}

//监听键盘收起事件，用于将页面恢复原状
-(void)keyBoardHide:(NSNotification *) anotification{
    if (!self.hpUIDelegate) {
        return;
    }
    
    Screen * keyBordScreen = (Screen*)[self.hpUIDelegate topScreen];
	if (keyBordScreen!=nil) {
		[keyBordScreen hideKeyBoardUI];
	}
}

-(void)getAddressWithGPS:(CallbackData*)callBack{
    if (self.hpUtilDelegate && [self.hpUtilDelegate respondsToSelector:@selector(userCurrentLocationSuccess:fail:timeoutInterval:)]) {
        
        [self.hpUtilDelegate userCurrentLocationSuccess:^(CLLocationCoordinate2D userLocationCoordinate,NSDictionary *address) {
            
            NSMutableDictionary* resultAddr = [NSMutableDictionary dictionaryWithCapacity:2];
            if (address) {
                resultAddr = [NSMutableDictionary dictionaryWithDictionary:address];
            }
            [resultAddr setObject:[NSString stringWithFormat:@"%f",userLocationCoordinate.latitude] forKey:KLatitudeKey];
            [resultAddr setObject:[NSString stringWithFormat:@"%f",userLocationCoordinate.longitude] forKey:KLongitudeKey];
            
            if (callBack && callBack.target && [callBack.target respondsToSelector:callBack.callback]) {
                [callBack.target performSelector:callBack.callback withObject:resultAddr];
            }
            
        } fail:^(NSError *error) {
            if (callBack && callBack.target && [callBack.target respondsToSelector:callBack.callback]) {
                [callBack.target performSelector:callBack.callback withObject:nil];
            }
        } timeoutInterval:0];
        
    }else{
        if (callBack && callBack.target && [callBack.target respondsToSelector:callBack.callback]) {
            [callBack.target performSelector:callBack.callback withObject:nil];
        }
    }
}
- (BOOL)doCheckGPSStatus{
    // 取得获取定位的权限
    CLAuthorizationStatus locStatus = [CLLocationManager authorizationStatus];
    if (![CLLocationManager locationServicesEnabled]
        || locStatus == kCLAuthorizationStatusRestricted
        || locStatus == kCLAuthorizationStatusDenied) {
        return NO;
    }
    return YES;
}
-(void)getAddressWithGPSBlock:(void(^)(NSString* , NSString* , NSString* , NSError* ))addressBlock{
    if (!self.hpUtilDelegate || ![self.hpUtilDelegate respondsToSelector:@selector(userCurrentLocationSuccess:fail:timeoutInterval:)]) {
        addressBlock(nil, nil, nil, [NSError errorWithDomain:@"no delegate found" code:-1 userInfo:nil]);
        return;
    }
    
    if (![self doCheckGPSStatus]) {
        addressBlock(nil, nil, nil, [NSError errorWithDomain:@"no delegate found" code:-2 userInfo:@{@"errMessage": @"用户不允许定位"}]);
        return;

    }
    
    [self.hpUtilDelegate userCurrentLocationSuccess:^(CLLocationCoordinate2D userLocationCoordinate, NSDictionary *address) {
        addressBlock([NSString stringWithFormat:@"%f",userLocationCoordinate.latitude],
                     [NSString stringWithFormat:@"%f",userLocationCoordinate.longitude],
                     [NSString stringWithFormat:@"%@|%@|%@|%@", [address objectForKey:KStateKey],
                      [address objectForKey:KCityKey],
                      [address objectForKey:KSubLocalityKey],
                      [address objectForKey:KAddressKey]],nil);
    } fail:^(NSError *error) {
        addressBlock(nil, nil, nil, error);
    } timeoutInterval:0];
}

@end
